package com.itany.nmms.service.impl;

import com.itany.nmms.constant.StatusConstant;
import com.itany.nmms.dao.StaffMapper;
import com.itany.nmms.entity.Staff;
import com.itany.nmms.entity.StaffExample;
import com.itany.nmms.exception.CodeErrorException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.exception.StaffNotExistException;
import com.itany.nmms.factory.ObjectFactory;
import com.itany.nmms.service.StaffService;
import com.itany.nmms.util.MD5Util;
import com.itany.nmms.util.ParameterUtil;

import java.util.List;

/**
 * @author 石小俊
 * @date 2023年11月08日 13:38
 */
public class StaffServiceImpl implements StaffService {

    @Override
    public Staff login(String loginName, String password, String role, String code, String image) throws RequestParameterErrorException, CodeErrorException, StaffNotExistException {
        // 由于当前dao是通过当前SqlSession获取的
        // 而每一个业务完成之后,均会关闭当前SqlSession
        // 因此,应该在当前业务中获取对应的dao
        StaffMapper staffMapper = (StaffMapper) ObjectFactory.getObject("staffMapper");

        if(ParameterUtil.isNull(loginName) || ParameterUtil.isNull(password) || ParameterUtil.isNull(role) || ParameterUtil.isNull(code) || ParameterUtil.isNull(image)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        // 判断验证码是否正确
        if(!code.equals(image)){
            throw new CodeErrorException("验证码不正确");
        }

        // 判断账号密码是否正确
        StaffExample example = new StaffExample();
        example.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password))
                .andRoleEqualTo(role)
                // 只有在职的员工才能登陆
                .andIsValidEqualTo(StatusConstant.STAFF_IS_VALID_YES);
        List<Staff> staffs = staffMapper.selectByExample(example);

        if(staffs.isEmpty()){
            throw new StaffNotExistException("账号或密码错误");
        }
        return staffs.get(0);
    }
}
